package me.servlet;

import me.domain.Student;
import me.service.StudentService;
import me.service.impl.StudentServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 用于显示首页信息的servlet
 */
@WebServlet("/indexServlet")
public class IndexServlet extends HttpServlet {

    //实例化StudentService对象
//    private StudentService studentService = new StudentServiceImpl();
    //使用工厂创建StudentService对象
//    private StudentService studentService = FactoryServiceImpl.getInstance().createStudentService();
    //通过工厂类获取StudentService对象 使用多例  如果需要单例需要写在方法内部
//    private StudentService studentService = (StudentService)Factory.getBeans("studentService");
    //通过spring容器获取容器对象
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
    //通过容器获取studentDao对象
    StudentService studentService = ac.getBean("studentService", StudentServiceImpl.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取所有的学生信息
        List<Student> studentList = studentService.getAllStudents();
        //将所有的学生信息保存在session中
        request.getSession().setAttribute("STUDENT_LIST",studentList);
        //转发到首页面
        request.getRequestDispatcher("index.jsp").forward(request,response);
    }
}
